package com.hangzhou.welbeing.welbeinginstrument.activity;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.conn.BleCharacterCallback;
import com.clj.fastble.data.ScanResult;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.tools.BluetoothService;
import com.hangzhou.welbeing.welbeinginstrument.utils.Utils;
import com.tuyenmonkey.mkloader.MKLoader;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 时间 2017 年 08 月 10.
 * 作者 Administrator  刘传华
 * 公司 杭州惟君医疗科技有限公司
 * 包名 com.hangzhou.welbeing.pregnant.welbeing_pregnant.activity
 * 工程名 welbeing_pregnant
 */
public class RadiationDetectorActivity extends Activity {
    private static final String TAG ="RadiationDetectorActivity" ;
    @Bind(R.id.activity_radiation_dector_iv_return)
    ImageView activityRadiationDectorIvReturn;
    @Bind(R.id.activity_radiation_dector_tv_low_frequency_test)
    TextView activityRadiationDectorTvLowFrequencyTest;
    @Bind(R.id.activity_radiation_dector_tv_high_frequency_test)
    TextView activityRadiationDectorTvHighFrequencyTest;
    @Bind(R.id.activity_radiation_dector_begin_testing)
    TextView activityRadiationDectorBeginTesting;
    @Bind(R.id.activity_radiation_dector_iv_security)
    ImageView activityRadiationDectorIvSecurity;
    @Bind(R.id.activity_radiation_dector_iv_warning)
    ImageView activityRadiationDectorIvWarning;
    @Bind(R.id.activity_radiation_dector_iv_peril)
    ImageView activityRadiationDectorIvPeril;

    @Bind(R.id.activity_radiation_dector_mkloader)
    MKLoader activityRadiationDectorMkloader;
/*
    @Bind(R.id.activity_radiation_dector_low_myview)
    MyView activityRadiationLowMyview;*/

//    @Bind(R.id.activity_radiation_dector_high_myview)
//    MyView activityRadiationHighMyview;

    private BluetoothService mBluetoothService;
    private String SERVICES_UUID = "0000180d-0000-1000-8000-00805f9b34fb";
    private String CHARECTERISTIC_UUID = "00002a37-0000-1000-8000-00805f9b34fb";
    private String[] names = new String[]{"Heart Rate Sensor"};
    private  Boolean flag = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radiation_dector);
        ButterKnife.bind(this);


        Utils.setStatusBar(this,false,false);
        Utils.setStatusTextColor(true,this);

//        activityRadiationLowMyview.setCircleColor(Color.parseColor("#2BB7FC"));
//        activityRadiationHighMyview.setCircleColor(Color.parseColor("#2BB7FC"));
    }

    @OnClick({R.id.activity_radiation_dector_iv_return, R.id.activity_radiation_dector_begin_testing})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_radiation_dector_iv_return:
                finish();
                break;
            case R.id.activity_radiation_dector_begin_testing: //开始测试
                String trim = activityRadiationDectorBeginTesting.getText().toString().trim();
                if(trim.equals("开始测试")){
                    checkPermissions();
                    activityRadiationDectorBeginTesting.setText("停止测试");
                    flag = true;
                    activityRadiationDectorMkloader.setVisibility(View.VISIBLE);
                }else{
                    activityRadiationDectorBeginTesting.setText("开始测试");
                    flag = false;
                    activityRadiationDectorMkloader.setVisibility(View.GONE);
                }

                break;
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (mBluetoothService == null) {
                    bindService();
                } else {
                    mBluetoothService.scanDevice();
                }
                break;
        }
    }
    private void checkPermissions() {
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, 12);
        }
    }
    @Override
    public final void onRequestPermissionsResult(int requestCode,
                                                 @NonNull String[] permissions,
                                                 @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 12:
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            onPermissionGranted(permissions[i]);
                        }
                    }
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService();
        if (mBluetoothService != null) {
            mBluetoothService.cancelScan();
        }

    }

    /**----------------------------------------------------------------*/

    private void bindService() {
        Intent bindIntent = new Intent(this, BluetoothService.class);
        this.bindService(bindIntent, mFhrSCon, Context.BIND_AUTO_CREATE);
    }
    private void unbindService() {
        if(mBluetoothService != null){
            this.unbindService(mFhrSCon);
        }
    }
    private ServiceConnection mFhrSCon = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBluetoothService = ((BluetoothService.BluetoothBinder) service).getService();
            mBluetoothService.setScanCallback(callback);
            mBluetoothService.scanAndConnect3(names);
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBluetoothService = null;
        }
    };
    private BluetoothService.Callback callback = new BluetoothService.Callback() {
        @Override
        public void onStartScan() {Log.e(TAG, "onStartScan()----------->");}
        @Override
        public void onScanning(ScanResult result) {Log.e(TAG, "onScanning()----------->");}
        @Override
        public void onScanComplete() {Log.e(TAG, "onScanComplete()----------->");}
        @Override
        public void onConnecting() {  Log.e(TAG, "onConnecting()----------->");}
        @Override
        public void onConnectFail() {
            Toast.makeText(RadiationDetectorActivity.this, "连接失败", Toast.LENGTH_LONG).show();
        }
        @Override
        public void onDisConnected() {
            Toast.makeText(RadiationDetectorActivity.this, "连接断开", Toast.LENGTH_LONG).show();
        }
        @Override
        public void onServicesDiscovered() {
            Log.e(TAG, "onServicesDiscovered()----------->");
            Opencurser();
        }
    };
    private void Opencurser() {
        Toast.makeText(RadiationDetectorActivity.this, "开始读取辐射值", Toast.LENGTH_LONG).show();
        mBluetoothService.notify(SERVICES_UUID,CHARECTERISTIC_UUID,
                new BleCharacterCallback() {
                    @Override
                    public void onSuccess(final BluetoothGattCharacteristic characteristic) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                if(flag) {
                                    activityRadiationDectorMkloader.setVisibility(View.GONE);
                                    /**
                                     * a 低频辐射值
                                     * b 高频辐射值
                                     * */
                                    String valueOf = String.valueOf(HexUtil.encodeHex(characteristic.getValue()));
                                    String sublowstring = valueOf.substring(4, 8);
                                    try {
                                        int   parselowInt = Integer.parseInt(sublowstring);
                                       // activityRadiationHighMyview.setAngel(parselowInt);
                                        activityRadiationDectorTvLowFrequencyTest.setText(parselowInt + "");
                                    } catch (NumberFormatException e) {
                                    }

                                    String subhighstring = valueOf.substring(12, valueOf.length());
                                    try {
                                        int  parsehighInt = Integer.parseInt(subhighstring);
                                        activityRadiationDectorTvHighFrequencyTest.setText(parsehighInt + "");
                                       // activityRadiationLowMyview.setAngel(parsehighInt);
                                    } catch (NumberFormatException e) {
                                    }




                                }
                            }
                        });
                    }
                    @Override
                    public void onFailure(final BleException exception) {}
                    @Override
                    public void onInitiatedResult(boolean result) {}
                });
    }
}
